/*
 * Copyright 2020-11-16 Baheal
 * @(#)CQMailUtil.java
 */
package com.byyy.ccts.core.utils.cq;

import com.byyy.ccts.core.base.ILogBase;
import com.byyy.ccts.core.utils.CacheUtils;
import com.byyy.ccts.core.utils.JeewebPropertiesUtil;
import com.byyy.ccts.core.utils.SpringContextHolder;
import com.byyy.ccts.core.utils.StringUtils;
import com.byyy.ccts.core.utils.http.HttpUtils;
import com.byyy.ccts.modules.sys.entity.Dict;
import com.byyy.ccts.modules.sys.entity.TZParam;
import com.byyy.ccts.modules.sys.service.IDictService;
import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @author liyongbo
 * @version 1.0
 * @date 2020-11-16 10:32
 * @description：
 */
public class CQMailUtils implements ILogBase {
    /**
     * 第三方appId
     */
    private static String appId = JeewebPropertiesUtil.getConfig("cq.mail.appId");;

    /**
     * 第三方app 密码
     */
    private static String appSecuret = JeewebPropertiesUtil.getConfig("cq.mail.appSecuret");;

    /**
     * 数据中心Id
     */
    private static String accountId = JeewebPropertiesUtil.getConfig("cq.mail.accountId");;

    /**
     * API访问_前缀地址
     */
    private static String apiPrefixUrl = JeewebPropertiesUtil.getConfig("cq.api.prefix.address");;

    /**
     * 获取应用token_后缀地址
     */
    private static String appTokenSuffixUrl = JeewebPropertiesUtil.getConfig("cq.api.appToken.suffix.address");;

    /**
     * 获取应用accessToken_后缀地址
     */
    private static String accessTokenSuffixUrl = JeewebPropertiesUtil.getConfig("cq.api.accessToken.suffix.address");;

    /**
     * 发送邮件_后缀地址
     */
    private static String sendMailSuffixAddress = JeewebPropertiesUtil.getConfig("cq.mail.send.suffix.address");;

    /**
     * 邮件发送人
     */
    private static String sender = JeewebPropertiesUtil.getConfig("cq.mail.sender");;

    /**
     * 发送邮件-通过CODE指定邮件发送人员
     * @param code
     * @param title
     * @param content
     * @return
     */
    public static boolean sendMail(String code, String title, String content) {
        // 获取邮件发送人列表
        IDictService dictService = SpringContextHolder.getBean(IDictService.class);
        List<Dict> mailSendTo = dictService.selectDictUsedListByGCode(code, null);

        if (mailSendTo == null || mailSendTo.size() < 1) {
            logger.error("邮件发送人为空！");
            return false;
        }
        StringBuilder sendTo = new StringBuilder();
        for (Dict temp : mailSendTo) {
            sendTo.append(temp.getValue()).append(",");
        }

        return sendMailTo(sendTo.toString(), title, content);
    }

    /**
     * 发送邮件
     * @param sendTo
     * @param title
     * @param content
     * @return
     */
    public static boolean sendMailTo(String sendTo, String title, String content) {
        // 获取token
        String appToken = (String) CacheUtils.get(CacheUtils.USER_CACHE, "cq.apptoken");
        String accessToken = (String) CacheUtils.get(CacheUtils.USER_CACHE, "cq.accessToken");
        if (StringUtils.isEmpty(appToken)) {
            appToken = getAppToken();
            if (StringUtils.isEmpty(appToken)) {
                return false;
            }
        }
        if (StringUtils.isEmpty(accessToken)) {
            accessToken = getAccessToken(sender, appToken);
            if (StringUtils.isEmpty(accessToken)) {
                return false;
            }
        }

        // 发送邮件,发送失败的情况，重新获取token，下次再发送
        return sendCQMail(sendTo, title, content, accessToken);
    }

    /**
     * 获取APPToken
     *
     * @return
     */
    private static String getAppToken() {
        String appTokenUrl = apiPrefixUrl + appTokenSuffixUrl;
        String appToken = "";
        // 构建参数
        JSONObject tokenObj = new JSONObject();
        tokenObj.put("appId", appId);
        tokenObj.put("appSecuret", appSecuret);
        tokenObj.put("accountId", accountId);
        String ret = HttpUtils.httpsPostWithJson(apiPrefixUrl, appTokenUrl, tokenObj.toString());
        tokenObj = JSONObject.fromObject(ret);

        // 解析结果
        if (null != tokenObj) {
            String status = (String) tokenObj.get("state");
            if ("success".equals(status)) {
                JSONObject dataObj = (JSONObject) tokenObj.get("data");
                appToken = (String) dataObj.get("app_token");
                CacheUtils.put(CacheUtils.USER_CACHE, "cq.apptoken", appToken);
            }
            else {
                logger.error("获取AppToken失败!({})", tokenObj.toString());
            }
        }
        return appToken;
    }

    /**
     * 获取AccessToken
     *
     * @return
     */
    public static String getAccessToken(String sender, String appToken) {
        String accessTokenUrl = apiPrefixUrl + accessTokenSuffixUrl;
        String accessToken = null;
        // 构建参数
        JSONObject accessTokenPm = new JSONObject();
        accessTokenPm.put("user", sender);
        accessTokenPm.put("apptoken", appToken);
        accessTokenPm.put("accountId", accountId);
        accessTokenPm.put("usertype", "UserName");
        String ret = HttpUtils.httpsPostWithJson(apiPrefixUrl, accessTokenUrl, accessTokenPm.toString());
        accessTokenPm = JSONObject.fromObject(ret);

        // 解析结果
        if (null != accessTokenPm) {
            String status = (String) accessTokenPm.get("state");
            if ("success".equals(status)) {
                JSONObject dataObj = (JSONObject) accessTokenPm.get("data");
                accessToken = (String)  dataObj.get("access_token");
                CacheUtils.put(CacheUtils.USER_CACHE, "cq.accessToken", accessToken);
            }
            else {
                logger.error("获取AccessToken失败!({})", accessTokenPm.toString());
            }
        }
        return accessToken;
    }

    /**
     * 发送短信提醒
     * @param code
     * @param content
     */
    public static void sendMobileMsg(String code, String content){
        // 获取邮件发送人列表
        IDictService dictService = SpringContextHolder.getBean(IDictService.class);
        List<Dict> mailSendTo = dictService.selectDictUsedListByGCode(code, null);

        if (mailSendTo == null || mailSendTo.size() < 1) {
            logger.error("短信接收人为空！");
            return;
        }
        StringBuilder sendTo = new StringBuilder();
        for (Dict temp : mailSendTo) {
            if (StringUtils.isNotEmpty(temp.getRemarks())) {
                sendTo.append(temp.getRemarks()).append(",");
            }
        }
        if (StringUtils.isEmpty(sendTo.toString())) {
            return;
        }

        StringBuffer sbf = new StringBuffer();

        try {
            sbf.append("http://api.chanzor.com/send?account=baiyangyiyao-tz&password=D78EF12956F157F81F16A733E3933514&mobile=");
            sbf.append(sendTo.deleteCharAt(sendTo.length() - 1).toString());
            sbf.append("&content=");
            sbf.append(URLEncoder.encode(content + "【百洋医药】", "UTF-8"));

            String ret = HttpUtils.get(sbf.toString(), "");
            logger.debug("短信发送完毕，发送结果{}", ret);
        }
        catch (UnsupportedEncodingException e) {
            logger.error("短信发送失败！", e);
        }

    }

    /**
     * 发送苍穹邮件
     * @param sendTo
     * @param title
     * @param content
     * @return
     */
    private static boolean sendCQMail(String sendTo, String title, String content, String accessToken) {
        String sendMailUrl = apiPrefixUrl + sendMailSuffixAddress + "?access_token=" + accessToken;
        // 构建参数
        CQMailBean mail = new CQMailBean();
        mail.setContent(content);
        mail.setRecipients(sendTo);
        mail.setTitle(title);

        // 解析结果
        String ret = HttpUtils.httpsPostWithJson(apiPrefixUrl, sendMailUrl, JSONObject.fromObject(mail).toString());
        JSONObject obj = JSONObject.fromObject(ret);

        if (obj == null) {
            return false;
        }
        if ((Boolean) obj.get("success")) {
            return true;
        }
        else {
            logger.error("发送邮件失败!({})", obj.toString());
            return false;
        }
    }

}
